<template>
  <div class="flex flex-col h-full">
    <SearchContainer @reset="() => formRef.resetFields()" @search="searchData">
      <a-form ref="formRef" class="form-style-flex" :model="formState">
        <a-form-item name="zjm" label="" class="w-64 ml-2">
          <SelectTable
            v-model:value="formState.brName"
            type="患者"
            :search-params="{ stdate: dayjs().format('YYYY-MM-DD'), eddate: dayjs().format('YYYY-MM-DD') }"
            custom-input
            :maxlength="20"
            empty-close
            placeholder="姓名/助记码/卡号/手机号/身份证号"
            @select="onSelectPatient"
          />
        </a-form-item>
        <a-form-item name="stdate" label="日期范围" class="ml-4">
          <a-range-picker v-model:value="formState.dateRange" class="w-64" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @keydown.enter="onEnter" />
        </a-form-item>
      </a-form>
    </SearchContainer>
    <!-- @change="patientInfoChange" -->
    <PatientInfoHeader :patient-info="currentPatient" class="mt-2">
      <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
      <div>
        <div class="flex items-center">
          <LabelValue label="客户来源" :width="180" :value="currentPatient.pathName" />
          <LabelValue label="业务员" :width="180" :value="currentPatient.brYwyName" />
        </div>
        <div class="flex items-center">
          <LabelValue label="信息卡号" :width="180" :value="currentPatient.brId" />
        </div>
      </div>
    </PatientInfoHeader>
    <a-card class="flex-1 mt-2 overflow-y-auto">
      <div>
        <a-button type="primary" @click="Add">新增</a-button>
      </div>
      <div class="mt-4">
        <BaseTable
          :columns="columns"
          :loading="loading"
          :data-source="tableData"
          :row-class-name="getRowClass"
          :scroll="{ x: 2400 }"
          :extra-height="40"
          :pagination="pagination"
        >
          <template #bodyCell="{ column, index, record }">
            <template v-if="column.dataIndex === 'xh'"> {{ index + 1 }} </template>
            <template v-if="column.dataIndex === 'odKeratometric'">
              <span v-if="record.odKeratometricK1">{{ record.odKeratometricK1 }} / {{ record.odKeratometricK2 }} @ {{ record.odKeratometricAx }}</span>
            </template>
            <template v-if="column.dataIndex === 'osKeratometric'">
              <span v-if="record.osKeratometricK1">{{ record.osKeratometricK1 }} / {{ record.osKeratometricK2 }} @ {{ record.osKeratometricAx }}</span>
            </template>
            <template v-if="column.dataIndex === 'action'">
              <a-button type="link" size="small" @click="edit(record)">修改</a-button>
              <ConfirmModal description="确定删除?" @confirm="deleteData(record)">
                <a-button type="text" danger size="small"> 删除 </a-button>
              </ConfirmModal>
              <!-- <a-button type="link" size="small" danger @click="deleteData(record)">删除</a-button> -->
            </template>
          </template>
        </BaseTable>
      </div>
      <div class="flex flex-wrap">
        <div v-for="(item, index) in chatData" :key="index" class="w-2/6 h-64 mt-4">
          <LineChart v-if="item.dataX && item.dataX.length > 0" :idx="index" :resource-data="item" />
        </div>
      </div>
    </a-card>
  </div>
  <Edit v-model:open="editModalOpen" :row-data="rowData" :patient-info="currentPatient" @success="editSuccess" />
</template>
<script setup>
import { ref } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import SearchContainer from '@/components/SearchContainer'
import { post } from '@/utils/request'
import ConfirmModal from '@/components/ConfirmModal'
import Edit from './components/Edit'
import LineChart from './components/LineChart'

const formState = ref({
  status: '',
  stdate: dayjs().format('YYYY-MM-DD'),
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
})
const currentPatient = ref({})
const editModalOpen = ref(false)
const rowData = ref({})
const chatData = ref([])

const { loading, tableData, getData, pagination } = useTable({
  url: '/optometry/ooadolescentcheck/getOoAdolescentCheckList',
  immediate: false,
  formatParams: () => {
    return {
      brid: currentPatient.value.brId,
      stdate: formState.value.dateRange?.[0],
      eddate: formState.value.dateRange?.[1]
    }
  },
  formatResult: (result = []) => {
    return result
  },
  onSuccess: () => {
    formatChatData()
  }
})
const searchData = () => {
  if (!formState.value.brName) return message.error('请选择客户')
  getData()
}
const Add = () => {
  if (!currentPatient.value.brId) {
    message.error('请先选择客户')
    return
  }
  rowData.value = {}
  editModalOpen.value = true
}
const formatChatData = () => {
  let data = []
  if (tableData.value.length > 5) {
    data = tableData.value.slice(0, 5)
  } else {
    data = tableData.value
  }
  // {
  //   title: '',
  //   legendData:[]
  //   unit:'单位'
  //   dataX: [],
  //   dataY: [
  //     {
  //       name: '',
  //       data: '',
  //       color: ''
  //     }
  //   ]
  // }
  const height = {}
  const weight = {}
  const naked = {} //裸眼视力
  const diopter = {} //屈光度
  const astigmatism = {} //散光度
  const axisPosition = {} //轴位
  const nct = {} //nct
  const ocularAxis = {} //眼轴
  height.title = '身高'
  weight.title = '体重'
  naked.title = '裸眼视力'
  diopter.title = '屈光度'
  astigmatism.title = '散光度'
  axisPosition.title = '轴位'
  nct.title = 'NCT'
  ocularAxis.title = '眼轴'
  height.legendData = ['身高']
  weight.legendData = ['体重']
  naked.legendData = ['右眼(OD)', '左眼(OS)']
  diopter.legendData = ['右眼(OD)', '左眼(OS)']
  astigmatism.legendData = ['右眼(OD)', '左眼(OS)']
  axisPosition.legendData = ['右眼(OD)', '左眼(OS)']
  nct.legendData = ['右眼(OD)', '左眼(OS)']
  ocularAxis.legendData = ['右眼(OD)', '左眼(OS)']
  height.unit = '单位:cm'
  weight.unit = '单位:Kg'
  naked.unit = '单位:度数'
  diopter.unit = ''
  astigmatism.unit = ''
  axisPosition.unit = ''
  nct.unit = ''
  ocularAxis.unit = ''
  const dataX = data.map((item) => {
    return {
      value: item.chkTime,
      age: item.age
    }
  })
  height.dataX = dataX
  weight.dataX = dataX
  naked.dataX = dataX
  diopter.dataX = dataX
  astigmatism.dataX = dataX
  axisPosition.dataX = dataX
  nct.dataX = dataX
  ocularAxis.dataX = dataX
  const sh = [],
    tz = [],
    lyslz = [], //裸眼视力
    lysly = [],
    qgdz = [], //屈光度
    qgdy = [],
    sgdz = [], //散光度
    sgdy = [],
    zwz = [], //轴位
    zwy = [],
    nctz = [], //nct
    ncty = [],
    yzz = [], //眼轴
    yzy = []
  data.forEach((item) => {
    sh.push(Number(item.patientHeight))
    tz.push(Number(item.patientWeight))
    lyslz.push(Number(item.osVa))
    lysly.push(Number(item.odVa))
    qgdz.push(Number(item.osDiopter))
    qgdy.push(Number(item.odDiopter))
    sgdz.push(Number(item.osAstigmia))
    sgdy.push(Number(item.odAstigmia))
    zwz.push(Number(item.osAxis))
    zwy.push(Number(item.odAxis))
    nctz.push(Number(item.osNct))
    ncty.push(Number(item.odNct))
    yzz.push(Number(item.osEyeAxis))
    yzy.push(Number(item.odEyeAxis))
  })
  height.dataY = [{ name: '身高', data: sh, color: '#009dd9' }]
  weight.dataY = [{ name: '体重', data: tz, color: '#009dd9' }]
  naked.dataY = [
    { name: '右眼(OD)', data: lysly, color: '#0000ff' },
    { name: '左眼(OS)', data: lyslz, color: '#009dd9' }
  ]
  diopter.dataY = [
    { name: '右眼(OD)', data: qgdy, color: '#0000ff' },
    { name: '左眼(OS)', data: qgdz, color: '#009dd9' }
  ]
  astigmatism.dataY = [
    { name: '右眼(OD)', data: sgdy, color: '#0000ff' },
    { name: '左眼(OS)', data: sgdz, color: '#009dd9' }
  ]
  axisPosition.dataY = [
    { name: '右眼(OD)', data: zwy, color: '#0000ff' },
    { name: '左眼(OS)', data: zwz, color: '#009dd9' }
  ]
  nct.dataY = [
    { name: '右眼(OD)', data: ncty, color: '#0000ff' },
    { name: '左眼(OS)', data: nctz, color: '#009dd9' }
  ]
  ocularAxis.dataY = [
    { name: '右眼(OD)', data: yzy, color: '#0000ff' },
    { name: '左眼(OS)', data: yzz, color: '#009dd9' }
  ]
  chatData.value = [height, weight, naked, diopter, astigmatism, axisPosition, nct, ocularAxis]
}

const columns = [
  { title: '序号', dataIndex: 'xh', width: 50 },
  { title: '检查日期', dataIndex: 'chkTime', width: 120 },
  {
    title: '右眼（OD）',
    dataIndex: 'oprLevelName',
    children: [
      {
        title: '裸眼视力',
        align: 'center',
        dataIndex: 'odVa',
        width: 90
      },
      {
        title: '屈光度',
        align: 'center',
        dataIndex: 'odDiopter',
        width: 90
      },
      {
        title: '散光度',
        align: 'center',
        dataIndex: 'odAstigmia',
        width: 90
      },
      {
        title: '轴位',
        align: 'center',
        dataIndex: 'odAxis',
        width: 90
      },
      {
        title: '矫正视力',
        align: 'center',
        dataIndex: 'odCva',
        width: 90
      },
      {
        title: '眼病',
        align: 'center',
        dataIndex: 'odDiseases',
        width: 90
      },
      {
        title: 'NCT',
        align: 'center',
        dataIndex: 'odNct',
        width: 90
      },
      {
        title: '眼轴',
        align: 'center',
        dataIndex: 'odEyeAxis',
        width: 90
      },
      {
        title: '角膜曲率',
        align: 'center',
        dataIndex: 'odKeratometric',
        width: 100
      }
    ]
  },
  {
    title: '左眼（OS） ',
    dataIndex: 'oprLevelName',
    children: [
      {
        title: '裸眼视力',
        align: 'center',
        dataIndex: 'osVa',
        width: 90
      },
      {
        title: '屈光度',
        align: 'center',
        dataIndex: 'osDiopter',
        width: 90
      },
      {
        title: '散光度',
        align: 'center',
        dataIndex: 'osAstigmia',
        width: 90
      },
      {
        title: '轴位',
        align: 'center',
        dataIndex: 'osAxis',
        width: 90
      },
      {
        title: '矫正视力',
        align: 'center',
        dataIndex: 'osCva',
        width: 90
      },
      {
        title: '眼病',
        align: 'center',
        dataIndex: 'osDiseases',
        width: 90
      },
      {
        title: 'NCT',
        align: 'center',
        dataIndex: 'osNct',
        width: 90
      },
      {
        title: '眼轴',
        align: 'center',
        dataIndex: 'osEyeAxis',
        width: 90
      },
      {
        title: '角膜曲率',
        align: 'center',
        dataIndex: 'osKeratometric',
        width: 100
      }
    ]
  },
  { title: '身高', dataIndex: 'patientHeight', width: 100 },
  { title: '体重', dataIndex: 'patientWeight', width: 100 },
  { title: '全身病', dataIndex: 'patientDiseases', width: 100 },
  { title: '所在学校', dataIndex: 'patientSchool' },
  { title: '操作', dataIndex: 'action', fixed: 'right', width: 120 }
]
const getRowClass = (record) => {
  return record.status === '0' ? '' : 'table-row-readonly-not-last'
}
const onSelectPatient = (e) => {
  currentPatient.value = e
  formState.value.brName = e.brName
  getData()
}
const editSuccess = () => {
  getData()
}
const edit = (row) => {
  rowData.value = row
  editModalOpen.value = true
}
const deleteData = async (row) => {
  const { code, msg } = await post('/optometry/ooadolescentcheck/doDelOoAdolescentCheck', {
    id: row.id
  })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  getData()
}
const onEnter = (e) => {
  let dateString = e.target.value // 匹配YYYYMMDD格式
  const regex1 = /^\d{8}$/ // 匹配YYYYMMDD格式
  const regex2 = /^\d{4}-\d{2}-\d{2}$/ // 匹配YYYY-MM-DD格式
  const regex3 = /^\d{4}\/\d{2}\/\d{2}$/ // 匹配YYYY/MM/DD格式
  const regex4 = /^\d{4}\.\d{2}\.\d{2}$/ // 匹配YYYY.MM.DD格式
  // 检查日期字符串是否符合任何一个正则表达式
  const isValidDate = regex1.test(dateString) || regex2.test(dateString) || regex3.test(dateString) || regex4.test(dateString)
  if (regex4.test(dateString)) dateString = dateString.replace(/\./g, '-')
  if (e.target.placeholder === '开始日期') {
    isValidDate && (formState.value.dateRange[0] = dayjs(dateString).format('YYYY-MM-DD'))
  } else {
    isValidDate && (formState.value.dateRange[1] = dayjs(dateString).format('YYYY-MM-DD'))
  }
}
</script>
